{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 方法大全"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.4.1\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import time\n",
    "print(cv2.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture/a1.jpg\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cv_show(name, img):\n",
    "    cv2.imshow(name, img)\n",
    "    cv2.waitKey(0)\n",
    "    cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 灰度空间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a1.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "cv2.imshow('a', image)\n",
    "cv2.waitKey()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "cv2.imshow('a', gray)\n",
    "cv2.waitKey()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# HSV色彩空间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n",
    "cv_show('q', hsv)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 拆分通道"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 拆分bgr\n",
    "b, g, r = cv2.split(image)\n",
    "cv_show('q', b)\n",
    "cv_show('q', g)\n",
    "cv_show('e', r)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 拆分HSV\n",
    "h, s, v = cv2.split(image)\n",
    "cv_show('q', h)\n",
    "cv_show('w', s)\n",
    "cv_show('q', v)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 合并通道"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 合并BRY\n",
    "bgr = cv2.merge([b, r, b]) # 可以调整顺序\n",
    "cv_show('e', bgr)\n",
    "# 合并HSV\n",
    "hsv = cv2.merge([h, s, v])\n",
    "hsv_1 = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n",
    "cv_show('e', hsv_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 综合应用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a16.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n",
    "h, s, v = cv2.split(hsv)\n",
    "#[:, :] = 100\n",
    "#[:,:] = 100\n",
    "s[:, :]= 100\n",
    "hsv_1 = cv2.merge([h, s, v])\n",
    "image_1 = cv2.cvtColor(hsv_1, cv2.COLOR_HSV2BGR)\n",
    "cv_show('w', image_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# alpha通道"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#A是透明度要保存后才能看到改变\n",
    "image = cv2.imread('D:/picture/a11.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "bgra = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA)\n",
    "b, g, r, a = cv2.split(bgra)\n",
    "a[:,:] = 0\n",
    "bgra_1 = cv2.merge([b, g, r, a])\n",
    "image_1 = cv2.cvtColor(bgra_1, cv2.COLOR_BGRA2BGR)\n",
    "cv_show('q', bgra_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 线段的绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.ones((300, 300, 3), np.uint8)*225\n",
    "canvas = cv2.line(canvas, (50, 50), (250, 50), (255, 0, 0), 5)\n",
    "canvas = cv2.line(canvas, (50, 150), (250, 150), (0, 255, 0), 10)\n",
    "canvas = cv2.line(canvas, (50, 250), (250, 250), (0, 0, 255), 15)\n",
    "canvas = cv2.line(canvas, (150, 50), (150, 250), (0, 255, 255), 20)\n",
    "cv_show('w', canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 矩形的绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((300, 300, 3), np.uint8)\n",
    "canvas = cv2.rectangle(canvas, (50, 50), (200, 150), (255, 255, 0), 3)\n",
    "cv_show('q', canvas)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实心矩形\n",
    "canvas = cv2.rectangle(canvas, (50, 50), (200, 150), (255, 255, 0), -1)\n",
    "cv_show('w', canvas)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 绘制正方形\n",
    "canvas = cv2.rectangle(canvas, (50, 50), (250, 250), (0, 0, 255), 30)\n",
    "canvas = cv2.rectangle(canvas, (90, 90), (210, 210), (0, 255, 255), 30)\n",
    "canvas = cv2.rectangle(canvas, (120, 120), (180, 180), (225, 0, 255), 30)\n",
    "cv_show('w', canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 圆形的绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((100, 300, 3), np.uint8)\n",
    "canvas = cv2.circle(canvas, (50, 50), 30, (0, 0, 255), -1)\n",
    "canvas = cv2.circle(canvas, (150, 50), 30, (0, 255, 255), -1)\n",
    "canvas = cv2.circle(canvas, (250, 50), 30, (0, 255, 0), -1)\n",
    "cv_show('w', canvas)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 绘制同心圆\n",
    "canvas = np.zeros((300, 300, 3), np.uint8)\n",
    "center_X = int(canvas.shape[1]/2)\n",
    "center_Y = int(canvas.shape[0]/2)\n",
    "for r in range(0, 150, 30):\n",
    "    cv2.circle(canvas, (center_X, center_Y), r, (0, 255, 0), 5)\n",
    "cv2.imshow('q', canvas)\n",
    "cv2.waitKey()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 绘制随机实心圆\n",
    "canvas = np.zeros((300, 300, 3), np.uint8)\n",
    "for numbers in range(0, 28):\n",
    "    center_X = np.random.randint(0, high = 300)\n",
    "    center_Y = np.random.randint(0, high = 300)\n",
    "    radius = np.random.randint(11, high = 71)\n",
    "    color = np.random.randint(0, high = 256, size=(3,)).tolist()\n",
    "    cv2.circle(canvas, (center_X, center_Y), radius, color, -1)\n",
    "cv2.imshow('q', canvas)\n",
    "cv2.waitKey()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 多边形的绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((300, 300, 3), np.uint8)\n",
    "pts = np.array([[100, 50], [200, 50], [250, 250], [50, 250]], np.int32)\n",
    "canvas = cv2.polylines(canvas, [pts], True, (0, 0, 255), 5) # 闭合的\n",
    "cv_show('q', canvas)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((300, 300, 3), np.uint8)\n",
    "pts = np.array([[100, 50], [200, 50], [250, 250], [50, 250]], np.int32)\n",
    "canvas = cv2.polylines(canvas, [pts], False, (0, 0, 255), 5) # 不闭合\n",
    "cv_show('q', canvas_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 文字的绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((100, 300, 3), np.uint8)\n",
    "cv2.putText(canvas, \"python\", (20, 70), cv2.FONT_HERSHEY_TRIPLEX, 2, (255, 0, 0), 5)\n",
    "cv_show('q', canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 斜体文字的绘制\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((100, 300, 3), np.uint8)\n",
    "fontStyle = cv2.FONT_HERSHEY_TRIPLEX + cv2.FONT_ITALIC\n",
    "cv2.putText(canvas, \"TCW\", (20, 70), fontStyle, 2, (255, 55, 109), 5)\n",
    "cv_show('w', canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 文字的垂直镜像绘制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "canvas = np.zeros((200, 300, 3), np.uint8)\n",
    "fontStyle = cv2.FONT_HERSHEY_TRIPLEX + cv2.FONT_ITALIC\n",
    "cv2.putText(canvas, \"TCW\", (20, 70), fontStyle, 2, (255, 55, 109), 5)\n",
    "cv2.putText(canvas, \"TCW\", (20, 100), fontStyle, 2, (255, 55, 109), 5, 8, True)\n",
    "cv_show('w', canvas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 在图像上绘制文字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture/a13.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "fontStyle = cv2.FONT_HERSHEY_TRIPLEX\n",
    "cv2.putText(image, 'zhu yuan', (20, 90), fontStyle, 1, (0, 255, 255))\n",
    "cv_show('w', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 绘制动态图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#width, height = 200, 200\n",
    "#r = 20\n",
    "#x = r + 20\n",
    "#y = r + 100\n",
    "#x_offre = y_offre = 4\n",
    "#while cv2.waitKey(1) == -1:\n",
    "    #if x > width - r or x < r:\n",
    "       # x_offre *= -1\n",
    "   # if y > height - r or y < r:\n",
    "    #    y_offre *= -1\n",
    "   # x += x_offre\n",
    "   # y += y_offre\n",
    "   # image = cv2.imread(\"D:/picture/a13.jpg\")\n",
    "   # image = cv2.resize(image, (800, 500))\n",
    "   # cv2.circle(image, (x, y), r, (255, 0, 0), -1)\n",
    "   # cv2.imshow('w', image)\n",
    "   # time.sleep(1/60)\n",
    "# 会卡电脑"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图像的几何变换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 图像的缩放\n",
    "image = cv2.imread(\"D:/picture/a13.jpg\")\n",
    "cv_show('w', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.resize(image, (800, 500))\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fx与fy参数缩放图像\n",
    "image = cv2.imread('D:/picture/a11.jpg')\n",
    "image = cv2.resize(image, None, fx=1/3, fy=1/2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图像的翻转"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a15.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "image_1 = cv2.flip(image, 1)\n",
    "cv_show('q', image_1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_2 = cv2.flip(image, -1)\n",
    "cv_show('q', image_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_3 = cv2.flip(image, 0)\n",
    "cv_show('q', image_3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 放射变换\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 平移\n",
    "image = cv2.imread('D:/picture/a3.jpg')\n",
    "rows = len(image)\n",
    "cols = len(image[0])\n",
    "M = np.float32([[2, 0, 5], [0, 1, 1]])\n",
    "dst = cv2.warpAffine(image, M, (800, 500))\n",
    "cv_show('w', dst)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 旋转\n",
    "image = cv2.imread('D:/picture/a3.jpg')\n",
    "rows = len(image)\n",
    "cols = len(image[0])\n",
    "center = (rows/2, cols/2)\n",
    "M = cv2.getRotationMatrix2D(center, 30, 0.8)\n",
    "dst = cv2.warpAffine(image, M, (cols, rows))\n",
    "cv_show('q', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 倾斜变换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a6.jpg')\n",
    "image = cv2.resize(image, (450, 800))\n",
    "rows = len(image)\n",
    "cols = len(image[0])\n",
    "p1 = np.zeros((3, 2), np.float32)\n",
    "p1[0] = [0, 0]\n",
    "p1[1] = [cols-1, 0]\n",
    "p1[2] = [1, rows-1]\n",
    "p2 = np.zeros((3, 2), np.float32)\n",
    "p2[0] = [50, 0]\n",
    "p2[1] = [cols-1, 0]\n",
    "p2[2] = [1, rows-1]\n",
    "M = cv2.getAffineTransform(p1, p2)\n",
    "dst = cv2.warpAffine(image, M, (cols, rows))\n",
    "cv_show('2', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 透视变换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a9.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "rows = len(image)\n",
    "cols = len(image[0])\n",
    "p1 = np.zeros((4, 2), np.float32)\n",
    "p1[0] = [0, 0]\n",
    "p1[1] = [cols-1, 0]\n",
    "p1[2] = [0, rows-1]\n",
    "p1[3] = [cols-1, rows-1]\n",
    "p2 = np.zeros((4, 2), np.float32)\n",
    "p2[0] = [90, 0]\n",
    "p2[1] = [cols-90, 0]\n",
    "p2[2] = [0, rows-1]\n",
    "p2[3] = [cols-1, rows-1]\n",
    "M = cv2.getPerspectiveTransform(p1, p2)\n",
    "dst = cv2.warpPerspective(image, M,(cols, rows))\n",
    "cv_show('q', dst)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二值化处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 小于阈值的变为0（纯黑），大于阈值的变为255（可调）\n",
    "image = cv2.imread('D:/picture/a52.jpg', 0)\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)\n",
    "cv_show('q', dst1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 阈值更改\n",
    "t2, dst2 = cv2.threshold(image, 220, 255, cv2.THRESH_BINARY)\n",
    "cv_show('q', dst2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 最大值更改\n",
    "t2, dst3 = cv2.threshold(image, 127, 200, cv2.THRESH_BINARY)\n",
    "cv_show('w', dst3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 彩图二值化处理\n",
    "image = cv2.imread('D:/picture/a32.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 200, cv2.THRESH_BINARY)\n",
    "cv_show('q', dst1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 反二值化处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 就是反过来\n",
    "image = cv2.imread('D:/picture/a26.jpg', 0) # 也可以处理彩图\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)\n",
    "cv_show('w', dst1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 零处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 小于或等于阈值的变为0，大于的保持不变\n",
    "image = cv2.imread('D:/picture/a29.jpg', 0) # 也可以处理彩图\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO)\n",
    "cv_show('w', dst1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 超出阈值零处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 大于阈值的变为0，小于或等于的不变\n",
    "image = cv2.imread('D:/picture/a23.jpg', 0) # 也可以处理彩图\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO_INV)\n",
    "cv_show('w', dst1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 截断处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 大于阈值变为和阈值一样的值，小于或等于的保持不变\n",
    "image = cv2.imread('D:/picture/a29.jpg', 0)\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) # 二值化\n",
    "t7, dst7 = cv2.threshold(image, 127, 255, cv2.THRESH_TRUNC)\n",
    "cv_show('w', dst7)\n",
    "cv_show('w', dst1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 自适应处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a33.jpg', 0) # 必须先把图像转为灰度图才能进行处理\n",
    "image = cv2.resize(image, (800, 500))\n",
    "athd = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 3)\n",
    "athd_2 = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 3)\n",
    "cv_show('w', athd)\n",
    "cv_show('q', athd_2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Otsu方法（寻找最合适的阈值,不一定是最好的阈值）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a32.jpg', 0) # 必须先把图像转为灰度图才能进行处理\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n",
    "cv_show('2', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 阈值处理的作用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a42.jpg',0) # 可以处理彩图\n",
    "image = cv2.resize(image, (800, 500))\n",
    "t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)\n",
    "t2, dst2 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)\n",
    "cv_show('q', dst1)\n",
    "cv_show('q', dst2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图像的运算"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 掩码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "mask = np.zeros((150, 150, 3), np.uint8)\n",
    "mask[50: 100, 20: 80, :] = 255\n",
    "cv_show('q', mask)\n",
    "mask[:,:,:] = 255\n",
    "mask[50: 100, 20:80,:] = 0\n",
    "cv_show('q', mask)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图像的加法运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture/a23.jpg\")\n",
    "image = cv2.resize(image, (300, 500))\n",
    "sum1 = image + image\n",
    "sum2 = cv2.add(image, image)\n",
    "cv_show('q', image)\n",
    "cv_show('w', sum1)\n",
    "cv_show('q', sum2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 三原色的叠加\n",
    "img1 = np.zeros((150, 150, 3), np.uint8)\n",
    "img1[:,:,0] = 255\n",
    "img2 = np.zeros((150, 150, 3), np.uint8)\n",
    "img2[:,:,1] = 255\n",
    "img3 = np.zeros((150, 150, 3), np.uint8)\n",
    "img3[:,:,2] = 255\n",
    "cv_show('q', img1)\n",
    "cv_show('w', img2)\n",
    "cv_show('q', img3)\n",
    "img = cv2.add(img1, img2)\n",
    "cv_show('q', img)\n",
    "image = cv2.add(img, img3)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 利用掩码遮盖相加的结果\n",
    "img1 = np.zeros((150, 150, 3), np.uint8)\n",
    "img1[:,:,0] = 255\n",
    "img2 = np.zeros((150, 150, 3), np.uint8)\n",
    "img2[:,:,2] = 255\n",
    "img = cv2.add(img1, img2)\n",
    "cv_show('q', img)\n",
    "m = np.zeros((150, 150, 1), np.uint8)\n",
    "m[50:100, 50:100, :] = 255\n",
    "cv_show('q', m)\n",
    "img = cv2.add(img1, img2, mask=m)\n",
    "cv_show('p', img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图像的位运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 按位与运算(同位只有11=1，其他的都等于0)\n",
    "image = cv2.imread(\"D:/picture/a41.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "mask = np.zeros(image.shape, np.uint8)\n",
    "mask[120:180,:,:] = 255\n",
    "mask[:,80:180,:] = 255\n",
    "img = cv2.bitwise_and(image, mask)\n",
    "cv_show('q', img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 按位或运算（同位只有00=0，其他的都等于1）\n",
    "image = cv2.imread('D:/picture/a36.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "mask = np.zeros(image.shape, np.uint8)\n",
    "mask[120:180, :, :] = 255\n",
    "mask[:,80:180, :] = 255\n",
    "img = cv2.bitwise_or(image, mask)\n",
    "cv_show('q', img)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 按位取反运算（单目运算：1变为0，0变为1）\n",
    "image = cv2.imread('D:/picture/a27.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "img = cv2.bitwise_not(image)\n",
    "cv_show('q', image)\n",
    "cv_show('q', img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 按位异或运算（同位上的数相同就取0，不同就取1）\n",
    "image = cv2.imread('D:/picture/a29.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "m = np.zeros(image.shape, np.uint8)\n",
    "m[120:180,:,:] = 255\n",
    "m[:,80: 180,:] = 255\n",
    "img = cv2.bitwise_xor(image, m)\n",
    "cv_show('q', img)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 利用异或运算对图像进行加密\n",
    "def encode(img, img_key):\n",
    "    result = img = cv2.bitwise_xor(img, img_key)\n",
    "    return result\n",
    "image = cv2.imread('D:/picture/a41.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "rows, colmns, channel = image.shape\n",
    "img_key = np.random.randint(0, 256, (rows, colmns, 3), np.uint8)\n",
    "cv_show('q', image)\n",
    "cv_show('e', img_key)\n",
    "result = encode(image, img_key)  # 对图像进行加密\n",
    "cv_show('q', result)\n",
    "result_1 = encode(result, img_key)\n",
    "cv_show('q', result_1) # 对图像解密"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 合并图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_1 = cv2.imread('D:/picture/a41.jpg')\n",
    "image_2 = cv2.imread('D:/picture/a52.jpg')\n",
    "image_3 = cv2.imread('D:/picture/a50.jpg')\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "image_2 = cv2.resize(image_2, (800, 500))\n",
    "image_3 = cv2.resize(image_3, (800, 500))\n",
    "img = cv2.addWeighted(image_1, 0.7, image_2, 0.3, 0)\n",
    "img_1 = cv2.addWeighted(img, 0.5, image_3, 0.5, 0)\n",
    "cv_show('q', img)\n",
    "cv_show('e', img_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 覆盖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_1 = cv2.imread('D:/picture/a52.jpg')\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "img = image_1[75:400, 100:260, :]\n",
    "cv_show('q', img)\n",
    "rows, colmns, channel = img.shape\n",
    "image_1[10: 10+rows, 260: 260+colmns,:] = img # 先指定是上下的位置，后指定的是左右的位置\n",
    "cv_show('q', image_1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [],
   "source": [
    "def over_img(img, img_over, img_over_x, img_over_y):\n",
    "    img_h, img_w, img_p = img.shape\n",
    "    img_over_h, img_over_w, img_over_c = img_over.shape\n",
    "    if img_over_c <= 3:\n",
    "        img_over = cv2.cvtColor(img_over, cv2.COLOR_BGR2BGRA)\n",
    "    for w in range(0, img_over_w):\n",
    "        for h in range(0, img_over_h):\n",
    "            if img_over[h, w, 3] != 0:\n",
    "                for c in range(0, 3):\n",
    "                    x = img_over_x + w\n",
    "                    y = img_over_y + h\n",
    "                    if x >= img_w or y >= img_h:\n",
    "                        break\n",
    "                    img[y, x, c] = img_over[h, w, c]\n",
    "    return img\n",
    "\n",
    "image_1 = cv2.imread('D:/picture/a30.jpg')\n",
    "image_2 = cv2.imread('D:/picture/a13.jpg')\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "image_2 = cv2.resize(image_2, (800, 500))\n",
    "img = over_img(image_1, image_2, 95, 90)\n",
    "cv_show('w', img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 模板匹配"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 单模板匹配"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_1 = cv2.imread('D:/picture/a52.jpg')\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "img = image_1[75:400, 100:260, :]\n",
    "height, width, c = img.shape\n",
    "result = cv2.matchTemplate(image_1, img, cv2.TM_SQDIFF_NORMED)\n",
    "minValue, maxValue, minLoc, maxLoc = cv2.minMaxLoc(result)\n",
    "resultPoint1 = minLoc\n",
    "resultPoint2 = (resultPoint1[0]+width, resultPoint1[1]+height)\n",
    "cv_show('w', image_1)\n",
    "cv_show('q', img)\n",
    "cv2.rectangle(image_1, resultPoint1, resultPoint2, (0, 0, 255), 2)\n",
    "cv_show('q', image_1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 寻找最佳匹配结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "27073.64301300049\n",
      "41445.89618682861\n"
     ]
    }
   ],
   "source": [
    "image_1 = cv2.imread('D:/picture/a52.jpg')\n",
    "image_2 = cv2.imread('D:/picture/a28.jpg')\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "image_2 = cv2.resize(image_2, (800, 500))\n",
    "img = image_1[75:400, 100:260, :]\n",
    "cv_show('q', image_1)\n",
    "cv_show('q', image_2)\n",
    "cv_show('o', img)\n",
    "image = []\n",
    "image.append(image_1)\n",
    "image.append(image_2)\n",
    "a1 = cv2.matchTemplate(image[0], img, cv2.TM_SQDIFF_NORMED) # 平方差方法，越小的匹配越成功\n",
    "a2 = cv2.matchTemplate(image[1], img, cv2.TM_SQDIFF_NORMED)\n",
    "print(sum(sum(a1)))\n",
    "print(sum(sum(a2)))\n",
    "if sum(sum(a1)) < sum(sum(a2)):\n",
    "    cv_show('w', image_1)\n",
    "else:\n",
    "    cv_show('w', image_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "66\n",
      "相同的照片a53.jpg,a7.jpg,\n",
      "相同的照片a61.jpg,a65.jpg,\n"
     ]
    }
   ],
   "source": [
    "# 查找重复图像\n",
    "import os\n",
    "import sys\n",
    "PIC_PATH = 'D:/picture/'\n",
    "width, height = 100, 100\n",
    "pic_file = os.listdir(PIC_PATH)\n",
    "same_pic_index = []\n",
    "imgs = []\n",
    "has_same = set()\n",
    "count = len(pic_file)\n",
    "print(count)\n",
    "if count == 0:\n",
    "    sys.exit(0)\n",
    "for file_name in pic_file:\n",
    "    pic_name = PIC_PATH + file_name\n",
    "    img = cv2.imread(pic_name)\n",
    "    img = cv2.resize(img, (width, height))\n",
    "    imgs.append(img)\n",
    "\n",
    "for i in range(0, count-1):\n",
    "    if i in has_same:\n",
    "        continue\n",
    "    templ = imgs[i]\n",
    "    same = [i]\n",
    "    for j in range(1+i, count):\n",
    "        if j in has_same:\n",
    "            continue\n",
    "        pic = imgs[j]\n",
    "        result = cv2.matchTemplate(pic, templ, cv2.TM_CCOEFF_NORMED)\n",
    "        if result > 0.9:\n",
    "            same.append(j)\n",
    "            has_same.add(i)\n",
    "            has_same.add(j)\n",
    "    if len(same) > 1:\n",
    "        same_pic_index.append(same)\n",
    "            \n",
    "for same_list in same_pic_index:\n",
    "    text = \"相同的照片\"\n",
    "    for same in same_list:\n",
    "        text += str(pic_file[same])+\",\"\n",
    "    print(text)    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 同图像多目标匹配（1）\n",
    "image = cv2.imread('D:/picture/a8.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "cv_show('q', image)\n",
    "image_1 = image[100:150, 605:641, :]\n",
    "cv_show('q', image_1)\n",
    "height, width, c = image_1.shape\n",
    "result = cv2.matchTemplate(image, image_1, cv2.TM_CCOEFF_NORMED)\n",
    "for y in range(len(result)):\n",
    "    for x in range(len(result[y])):\n",
    "        if result[y][x] > 0.7:\n",
    "            cv2.rectangle(image, (x, y), (x+width, y+height), (0, 0, 255), 2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实例2\n",
    "import numpy as np\n",
    "import math\n",
    "image = cv2.imread('D:/picture_2/b1.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "cv_show('q', image)\n",
    "image_1 = image[40:60, 60: 80, :]\n",
    "cv_show('w', image_1)\n",
    "height, width, c = image_1.shape\n",
    "result = cv2.matchTemplate(image, image_1, cv2.TM_CCOEFF_NORMED)\n",
    "point_x = []\n",
    "point_y = []\n",
    "for y in range(len(result)):\n",
    "    for x in range(len(result[y])):\n",
    "        if result[y][x] > 0.55:\n",
    "            cv2.rectangle(image, (x, y), (x+width, y+height), (0, 0, 255), 2)\n",
    "            point_x.extend([x])\n",
    "            point_y.extend([y])\n",
    "start_x = 160\n",
    "start_y = 225\n",
    "place_Square = np.array([point_x[0], point_y[0]])\n",
    "place_start = np.array([start_x, start_y])\n",
    "minu = place_start - place_Square\n",
    "start_square = math.hypot(minu[0], minu[1])\n",
    "\n",
    "place_hi = np.array([point_x[1], point_y[1]])\n",
    "minu_a = place_hi - place_start\n",
    "start_hig = math.hypot(minu_a[0], minu_a[1])\n",
    "if start_square < start_hig:\n",
    "    cv2.line(image, (start_x, start_y), (point_x[0], point_y[0]), (0, 255, 0), 2)\n",
    "else:\n",
    "     cv2.line(image, (start_x, start_y), (point_x[1], point_y[1]), (0, 255, 0), 2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 匹配图像中的多个模板"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a112.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "cv_show('w', image)\n",
    "image_1 = image[20:130, 30:150, :]\n",
    "image_2 = image[170:320, 90:200, :]\n",
    "image_3 = image[100:220, 180:280, :]\n",
    "cv_show('q', image_1)\n",
    "cv_show('e', image_2)\n",
    "cv_show('w', image_3)\n",
    "def myMatch(img, templ):\n",
    "    height, width, c = templ.shape\n",
    "    result = cv2.matchTemplate(img, templ, cv2.TM_CCOEFF_NORMED)\n",
    "    loc = list()\n",
    "    for i in range(len(result)):\n",
    "        for j in range(len(result[i])):\n",
    "            if result[i][j] > 0.9:\n",
    "                loc.append((j, i, j+width, i+height))\n",
    "    return loc\n",
    "\n",
    "temple = list()\n",
    "temple.append(image_1)\n",
    "temple.append(image_2)\n",
    "temple.append(image_3)\n",
    "loc = list()\n",
    "for t in temple:\n",
    "    loc += myMatch(image, t)\n",
    "for i in loc:\n",
    "    cv2.rectangle(image, (i[0], i[1]), (i[2], i[3]), (255, 255, 255), 2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.82580537\n",
      "芽衣\n",
      "0.8613121\n",
      "芽衣\n",
      "0.8589455\n",
      "芽衣\n",
      "0.82337815\n",
      "芽衣\n",
      "0.86695796\n",
      "芽衣\n",
      "0.8162229\n",
      "芽衣\n",
      "0.8042184\n",
      "琪亚娜\n",
      "0.8589386\n",
      "琪亚娜\n",
      "0.88033587\n",
      "琪亚娜\n",
      "0.8324463\n",
      "琪亚娜\n",
      "0.8038579\n",
      "琪亚娜\n"
     ]
    }
   ],
   "source": [
    "image = cv2.imread('D:/picture/a112.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "cv_show('w', image)\n",
    "image_1 = image[20:130, 30:150, :]\n",
    "image_2 = image[170:320, 90:200, :]\n",
    "image_3 = image[100:220, 180:280, :]\n",
    "temple = []\n",
    "temple.append(image_1)\n",
    "temple.append(image_2)\n",
    "temple.append(image_3)\n",
    "for i in temple:\n",
    "    result = cv2.matchTemplate(image, i, cv2.TM_CCOEFF_NORMED)\n",
    "    for a in range(len(result)):\n",
    "        for b in range(len(result[a])):\n",
    "            if result[a][b] > 0.8:\n",
    "                print(result[a][b])\n",
    "                if 20 < b <100:\n",
    "                    print('芽衣')\n",
    "                elif 170 < b < 300:\n",
    "                    print('琪亚娜')\n",
    "                elif 100 < b < 220:\n",
    "                    print('鸭鸭')\n",
    "                break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 滤波器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 均值滤波器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a98.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "dst1 = cv2.blur(image, (3, 3))\n",
    "dst2 = cv2.blur(image, (5, 5))\n",
    "dst3 = cv2.blur(image, (90, 50)) # （）指定越大，图像会越模糊\n",
    "cv_show('w', image)\n",
    "cv_show('w', dst1)\n",
    "cv_show('q', dst2)\n",
    "cv_show('r', dst3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 中值滤波器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture/a203.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "dst1 = cv2.medianBlur(image, 3)\n",
    "dst2 = cv2.medianBlur(image, 5)\n",
    "dst3 = cv2.medianBlur(image, 9)\n",
    "cv_show('q', image)\n",
    "cv_show('e', dst1)\n",
    "cv_show('p', dst2)\n",
    "cv_show('q', dst3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 高斯滤波器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture/a189.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "dst1 = cv2.GaussianBlur(image, (5, 5), 0, 0)  # 写成0，0就会自动寻找适合的\n",
    "dst2 = cv2.GaussianBlur(image, (9, 9), 0, 0)\n",
    "dst3 = cv2.GaussianBlur(image, (15, 15), 0, 0)\n",
    "cv_show('w', image)\n",
    "cv_show('w', dst1)\n",
    "cv_show('e', dst2)\n",
    "cv_show('r', dst3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 双边滤波器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 较好的保留图像的边缘信息\n",
    "image = cv2.imread(\"D:/picture/a189.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "dst3 = cv2.GaussianBlur(image, (15, 15), 0, 0)\n",
    "dst1 = cv2.bilateralFilter(image, 10, 100, 100)  # 写成0，0就会自动寻找适合的\n",
    "cv_show('w', image)\n",
    "cv_show('e', dst1)\n",
    "cv_show('e', dst3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图像的腐蚀与膨胀"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 腐蚀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as py\n",
    "k = np.ones((3, 3), np.uint8)\n",
    "image = cv2.imread('D:/picture/a99.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "dst = cv2.erode(image, k)\n",
    "cv_show('w', image)\n",
    "cv_show('q', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 膨胀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a78.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "k = np.ones((9, 9), np.uint8)\n",
    "dst = cv2.dilate(image, k)\n",
    "cv_show('w', image)\n",
    "cv_show('p', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 开运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 先腐蚀再膨胀\n",
    "image = cv2.imread('D:/picture/a199.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "k = np.ones((5, 5), np.uint8)\n",
    "dst = cv2.erode(image, k)\n",
    "dst = cv2.dilate(dst, k)\n",
    "cv_show('e', image)\n",
    "cv_show('p', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 闭运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "#先膨胀再腐蚀\n",
    "image = cv2.imread('D:/picture/a179.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "#t1, dst1 = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)\n",
    "k = np.ones((15, 15), np.uint8)\n",
    "dst = cv2.dilate(image, k)\n",
    "dst = cv2.erode(dst, k)\n",
    "cv_show('w', image)\n",
    "cv_show('q', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 梯度运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 原图的膨胀图减腐蚀图\n",
    "image = cv2.imread('D:/picture/a106.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "k = np.ones((5, 5), np.uint8)\n",
    "dst = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, k)\n",
    "cv_show('q', image)\n",
    "cv_show('q', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 顶帽运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 只剩下图像的外部细节\n",
    "image = cv2.imread('D:/picture/a135.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "k = np.ones((5, 5), np.uint8)\n",
    "dst = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, k)\n",
    "cv_show('q', image)\n",
    "cv_show('r', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 黑帽运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 留下图像的内部细节\n",
    "image = cv2.imread('D:/picture/a133.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "k = np.ones((5, 5), np.uint8)\n",
    "dst = cv2.morphologyEx(image, cv2.MORPH_BLACKHAT, k)\n",
    "cv_show('q', image)\n",
    "cv_show('r', dst)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图形检测"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 图形的轮廓"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a235.jpg')\n",
    "image = cv2.resize(image, (280, 500))\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "t, vinary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n",
    "e, contours, hierarchy = cv2.findContours(vinary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)  # 必须传入二值图像\n",
    "cv2.drawContours(image, contours, -1, (0, 0, 255), 1)\n",
    "cv_show('p', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture/a222.jpg')\n",
    "image = cv2.resize(image, (280, 500))\n",
    "image = cv2.medianBlur(image, 5)\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "t, vinary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n",
    "cv_show('q', image)\n",
    "cv_show('w', vinary)\n",
    "e, conrouts, gierardhy = cv2.findContours(vinary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n",
    "cv2.drawContours(image, conrouts, -1, (0, 0, 255), 1)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 轮廓拟合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 矩形包围框\n",
    "image = cv2.imread('D:/picture/a129.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "t, vinary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n",
    "e, conrouts, hierarchy = cv2.findContours(vinary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n",
    "x, y, w, h = cv2.boundingRect(conrouts[3])\n",
    "cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 圆形包围框\n",
    "image = cv2.imread('D:/picture/a133.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "t, vinary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n",
    "e, conrouts, hierarchy = cv2.findContours(vinary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n",
    "center, radius = cv2.minEnclosingCircle(conrouts[0])\n",
    "x = int(round(center[0]))\n",
    "y = int(round(center[1]))\n",
    "cv2.circle(image, (x, y), int(radius), (0, 0, 255), 2)\n",
    "cv_show('p', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 凸包\n",
    "image = cv2.imread('D:/picture/a183.jpg')\n",
    "image = cv2.resize(image, (250, 500))\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "t, vinary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n",
    "e, conrouts, hierarchy = cv2.findContours(vinary, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n",
    "hull = cv2.convexHull(conrouts[-1])\n",
    "cv2.polylines(image, [hull], True, (0, 0, 255), 2)\n",
    "cv_show('p', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Canny边缘检测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture/a190.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "r1 = cv2.Canny(image, 10, 50)\n",
    "r2 = cv2.Canny(image, 100, 200)\n",
    "r3 = cv2.Canny(image, 300, 500)\n",
    "# rall = np.hstack() 可以同时展示多个图像 \n",
    "cv_show('q', image)\n",
    "cv_show('p', r1)\n",
    "cv_show('q', r2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 霍夫变换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 检测图像直线\n",
    "image = cv2.imread(\"D:/picture/a213.jpg\")\n",
    "image = cv2.resize(image, (250, 500))\n",
    "o = image.copy()\n",
    "o = cv2.medianBlur(o, 5)\n",
    "gray = cv2.cvtColor(o, cv2.COLOR_BGR2GRAY)\n",
    "binary = cv2.Canny(o, 50, 150)\n",
    "lines = cv2.HoughLinesP(binary, 1, np.pi/180, 15, minLineLength=100, maxLineGap=18)\n",
    "for line in lines:\n",
    "    x1, y1, x2, y2 = line[0]\n",
    "    cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 检测图像圆环\n",
    "image = cv2.imread('D:/picture/a203.jpg')\n",
    "image = cv2.resize(image, (800, 500))\n",
    "cv_show('q', image)\n",
    "o = image.copy()\n",
    "o = cv2.medianBlur(o, 5)\n",
    "gray = cv2.cvtColor(o, cv2.COLOR_BGR2GRAY)\n",
    "circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 70, param1=100, param2=35, minRadius=10, maxRadius=50)\n",
    "circles = np.uint(np.around(circles))\n",
    "for c in circles[0]:\n",
    "    x, y, r = c\n",
    "    cv2.circle(image, (x, y), r, (0, 0, 255), 3)\n",
    "    cv2.circle(image, (x, y), 2, (0, 0, 255), 3)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 视频处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# VideoCapture类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 开启电脑内置摄像头并摄像\n",
    "capture = cv2.VideoCapture(0)\n",
    "while(capture.isOpened()):\n",
    "    retval, image = capture.read()\n",
    "    cv2.imshow(\"Video\", image)\n",
    "    key = cv2.waitKey(1)\n",
    "    if key == 32:\n",
    "        break\n",
    "capture.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 摄像灰度视频\n",
    "capture = cv2.VideoCapture(0)\n",
    "while(capture.isOpened()):\n",
    "    retval, image = capture.read()\n",
    "    image_Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "    if retval == True:\n",
    "        cv2.imshow(\"Video\", image)\n",
    "        cv2.imshow(\"Gray\", image_Gray)\n",
    "        key = cv2.waitKey(1)\n",
    "        if key == 32:\n",
    "            break\n",
    "capture.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "cap = cv2.VideoCapture(0)\n",
    "while(cap.isOpened()):\n",
    "    ret, frame = cap.read()\n",
    "    cv2.imshow(\"Video\", frame)\n",
    "    k = cv2.waitKey(1)\n",
    "    if k == 32:\n",
    "        cap.release()\n",
    "        cv2.destroyWindow(\"Video\")\n",
    "        cv2.imwrite(\"D:/picture_2/b2.png\", frame)\n",
    "        cv2.imshow('img', frame)\n",
    "        cv2.waitKey()\n",
    "        break\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 播放文件视频"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "video = cv2.VideoCapture(\"D:/picture/v1.mp4\")\n",
    "while(video.isOpened()):\n",
    "    retval, image = video.read()\n",
    "    cv2.namedWindow(\"video\", 0)\n",
    "    cv2.resizeWindow(\"video\", (800, 500))\n",
    "    if retval == True:\n",
    "        cv2.imshow('video', image)  # 名字要一样\n",
    "    else:\n",
    "        break\n",
    "    key = cv2.waitKey(30)\n",
    "    if key == 27:\n",
    "        break\n",
    "video.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将彩色视频转换为灰色视频\n",
    "video = cv2.VideoCapture(\"D:/picture/v1.mp4\")\n",
    "while(video.isOpened()):\n",
    "    retval, img_Clolr = video.read()\n",
    "    cv2.namedWindow(\"Gray\", 0)\n",
    "    cv2.resizeWindow(\"Gray\", (800, 500))\n",
    "    if retval == True:\n",
    "        img_Gray = cv2.cvtColor(img_Clolr, cv2.COLOR_BGR2GRAY)\n",
    "        cv2.imshow(\"Gray\", img_Gray)\n",
    "    else:\n",
    "        break\n",
    "    key = cv2.waitKey(35)\n",
    "    if key == 27:\n",
    "        break\n",
    "video.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 视频的暂停和继续"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "video = cv2.VideoCapture(\"D:/picture/v1.mp4\")\n",
    "while(video.isOpened()):\n",
    "    retval, image = video.read()\n",
    "    cv2.namedWindow(\"video\", 0)\n",
    "    cv2.resizeWindow(\"video\", (800, 500))\n",
    "    if retval == True:\n",
    "        cv2.imshow('video', image)\n",
    "    else:\n",
    "        break\n",
    "    key = cv2.waitKey(35)\n",
    "    if key == 32:\n",
    "        cv2.waitKey(0)\n",
    "        continue\n",
    "    if key == 27:\n",
    "        break\n",
    "video.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 获取视频的属性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "帧速率 23.99983505268005\n",
      "帧数 1164.0\n",
      "帧宽度 960\n",
      "帧高度 432\n"
     ]
    }
   ],
   "source": [
    "video = cv2.VideoCapture(\"D:/picture/v1.mp4\")\n",
    "fps = video.get(cv2.CAP_PROP_FPS)\n",
    "frame_Count = video.get(cv2.CAP_PROP_FRAME_COUNT)\n",
    "frame_Width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))\n",
    "frame_Height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n",
    "print(\"帧速率\",fps)\n",
    "print(\"帧数\",frame_Count)\n",
    "print(\"帧宽度\",frame_Width)\n",
    "print(\"帧高度\",frame_Height)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 动态显示视频属性\n",
    "video = cv2.VideoCapture(\"D:/picture/v1.mp4\")\n",
    "fps = video.get(cv2.CAP_PROP_FPS)\n",
    "frame_Num = 1\n",
    "while(video.isOpened()):\n",
    "    retval, frame = video.read()\n",
    "    cv2.namedWindow(\"video\", 0)\n",
    "    cv2.resizeWindow(\"video\", (800, 500))\n",
    "    if retval == True:\n",
    "        cv2.putText(frame, 'frame:'+str(frame_Num), (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 5)\n",
    "        cv2.putText(frame, 'second:'+str(round(frame_Num/fps, 2))+'s', (0, 200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 5)\n",
    "        cv2.imshow(\"video\", frame)\n",
    "    else:\n",
    "        break\n",
    "    key = cv2.waitKey(35)\n",
    "    frame_Num += 1\n",
    "    if key == 32:\n",
    "        cv2.waitKey(0)\n",
    "        continue\n",
    "    if key == 27:\n",
    "        break\n",
    "video.release()\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 保存视频文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "capture = cv2.VideoCapture(0)\n",
    "fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')\n",
    "output = cv2.VideoWriter('D:/picture_2/v1.avi', fourcc, 20, (640, 480))\n",
    "while(capture.isOpened()):\n",
    "    retval, frame = capture.read()\n",
    "    if retval == True:\n",
    "        output.write(frame)\n",
    "        cv2.imshow('frame', frame)\n",
    "    key = cv2.waitKey(1)\n",
    "    if key == 27:\n",
    "        break\n",
    "capture.release()\n",
    "output.release()\n",
    "cv2.destroyAllWindows()    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 录制并保存一段时长为10秒的视频\n",
    "capture = cv2.VideoCapture(0)\n",
    "fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')\n",
    "fps = 20\n",
    "output = cv2.VideoWriter('D:/picture_2/v2.avi', fourcc, 20, (640, 480))\n",
    "frame_Num = 10 * fps\n",
    "while(capture.isOpened() and frame_Num > 0):\n",
    "    retval, frame = capture.read()\n",
    "    if retval == True:\n",
    "        output.write(frame)\n",
    "        cv2.imshow('frame', frame)\n",
    "    key = cv2.waitKey(1)\n",
    "    frame_Num -= 1\n",
    "capture.release()\n",
    "output.release()\n",
    "cv2.destroyAllWindows()    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "录制完成\n"
     ]
    }
   ],
   "source": [
    "# 保存视频文件中前10秒的视频\n",
    "video = cv2.VideoCapture(\"D:/picture/v1.mp4\")\n",
    "fps = video.get(cv2.CAP_PROP_FPS)\n",
    "size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)),\n",
    "         int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n",
    "fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')\n",
    "output = cv2.VideoWriter('D:/picture_2/v3.mp4', fourcc, fps, size)\n",
    "frame_Num = 10 * fps\n",
    "while(video.isOpened() and frame_Num > 0):\n",
    "    retval, frame = video.read()\n",
    "    if retval == True:\n",
    "        output.write(frame)\n",
    "    frame_Num -= 1\n",
    "print('录制完成')\n",
    "video.release()\n",
    "output.release()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 人脸检测和人脸识别"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 分析人脸位置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "face_cascade = cv2.CascadeClassifier(\"C:/Users/baohu/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml\")\n",
    "image = cv2.imread(\"D:/picture_2/b10.jpg\")\n",
    "image = cv2.resize(image, (350, 500))\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))\n",
    "for (x, y, w, h) in faces:\n",
    "    cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)\n",
    "cv_show('q', image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 墨镜特效\n",
    "def overlay_img(img, img_over, img_over_x, img_over_y):\n",
    "    img_h, img_w, img_p = img.shape\n",
    "    img_over_h, img_over_w, img_over_c = img_over.shape\n",
    "    if img_over_c == 3:\n",
    "        img_over = cv2.cvtColor(img_over, cv2.COLOR_BGR2BGRA)\n",
    "    for w in range(0, img_over_w):\n",
    "        for h in range(0, img_over_h):\n",
    "            if img_over[h, w, 3] != 0:\n",
    "                for c in range(0, 3):\n",
    "                    x = img_over_x + w\n",
    "                    y = img_over_y + h\n",
    "                    if x >= img_w or y >= img_h:\n",
    "                        break\n",
    "                    img[y, x, c] = img_over[h, w, c]\n",
    "    return img\n",
    "face_img = cv2.imread('D:/picture_2/b2.jpg')\n",
    "glass_img = cv2.imread('D:/picture_2/b5.jpg')\n",
    "height, width, channel = glass_img.shape\n",
    "face_cascade = cv2.CascadeClassifier(\"C:/Users/baohu/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml\")\n",
    "gray = cv2.cvtColor(face_img, cv2.COLOR_BGR2GRAY)\n",
    "faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))\n",
    "for (x, y, w, h) in faces:\n",
    "    gw = w\n",
    "    gh = int(height * w / width)\n",
    "    glass_img = cv2.resize(glass_img, (gw, gh))\n",
    "    overlay_img(face_img, glass_img, x, y + int(h * 1 / 3))\n",
    "face_img = cv2.resize(face_img, (300, 500))\n",
    "cv_show('a', face_img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 检测其他内容"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 眼睛检测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread('D:/picture_2/b10.jpg')\n",
    "image = cv2.resize(image, (300, 500))\n",
    "eyeCascade = cv2.CascadeClassifier(\"C:/Users/baohu/Anaconda3/Lib/site-packages/cv2/data/haarcascade_eye.xml\")\n",
    "eyes = eyeCascade.detectMultiScale(image, 1.15)\n",
    "for (x, y, w, h) in eyes:\n",
    "    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 3)\n",
    "cv_show('w', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 猫脸检测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture_2/b6.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "catFaceCascade = cv2.CascadeClassifier(\"C:/Users/baohu/Anaconda3/Lib/site-packages/cv2/data/haarcascade_frontalcatface_extended.xml\")\n",
    "catFace = catFaceCascade.detectMultiScale(image, 1.15, 4)\n",
    "for (x, y, w, h) in catFace:\n",
    "    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 3)\n",
    "cv_show('w', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 行人检测\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture_2/b7.jpg\")\n",
    "image = cv2.resize(image, (300, 500))\n",
    "bodyCascade = cv2.CascadeClassifier(\"C:/Users/baohu/Anaconda3/Lib/site-packages/cv2/data/haarcascade_fullbody.xml\")\n",
    "bodys = bodyCascade.detectMultiScale(image, 1.15, 4)\n",
    "for (x, y, w, h) in bodys:\n",
    "    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 3)\n",
    "cv_show('w', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 车牌检测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = cv2.imread(\"D:/picture_2/b9.jpg\")\n",
    "image = cv2.resize(image, (800, 500))\n",
    "plateCascade = cv2.CascadeClassifier(\"C:/Users/baohu/Anaconda3/Lib/site-packages/cv2/data/haarcascade_russian_plate_number.xml\")\n",
    "plates = plateCascade.detectMultiScale(image, 1.15, 3)\n",
    "for (x, y, w, h) in plates:\n",
    "    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 3)\n",
    "cv_show('w', image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Eigenfaces人脸识别器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "confidence =23970.408942257425\n",
      "a_3\n"
     ]
    }
   ],
   "source": [
    "photos = list()\n",
    "lables = list()\n",
    "\n",
    "image_1 = cv2.imread(\"D:/picture/a23.jpg\", 0)\n",
    "image_2 = cv2.imread(\"D:/picture/a24.jpg\", 0)\n",
    "image_3 = cv2.imread(\"D:/picture/a25.jpg\", 0)\n",
    "\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "image_2 = cv2.resize(image_2, (800, 500))\n",
    "image_3 = cv2.resize(image_3, (800, 500))\n",
    "\n",
    "photos.append(image_1)\n",
    "lables.append(0)\n",
    "photos.append(image_2)\n",
    "lables.append(0)\n",
    "photos.append(image_3)\n",
    "lables.append(0)\n",
    "\n",
    "image_4 = cv2.imread(\"D:/picture/a33.jpg\", 0)\n",
    "image_5 = cv2.imread(\"D:/picture/a34.jpg\", 0)\n",
    "image_6 = cv2.imread(\"D:/picture/a35.jpg\", 0)\n",
    "\n",
    "image_4 = cv2.resize(image_4, (800, 500))\n",
    "image_5 = cv2.resize(image_5, (800, 500))\n",
    "image_6 = cv2.resize(image_6, (800, 500))\n",
    "\n",
    "photos.append(image_4)\n",
    "lables.append(1)\n",
    "photos.append(image_5)\n",
    "lables.append(1)\n",
    "photos.append(image_6)\n",
    "lables.append(1)\n",
    "\n",
    "names = {\"0\": \"a_2\", \"1\": \"a_3\"}\n",
    "recognizer = cv2.face.EigenFaceRecognizer_create()\n",
    "recognizer.train(photos, np.array(lables))\n",
    "\n",
    "image = cv2.imread(\"D:/picture/a45.jpg\", 0)\n",
    "image = cv2.resize(image, (800, 500))\n",
    "\n",
    "label, confidence = recognizer.predict(image)\n",
    "print(\"confidence =\" + str(confidence))\n",
    "print(names[str(label)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fisherfaces人脸识别器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "confidence =48.614343106024535\n",
      "a_2\n"
     ]
    }
   ],
   "source": [
    "photos = list()\n",
    "lables = list()\n",
    "\n",
    "image_1 = cv2.imread(\"D:/picture/a53.jpg\", 0)\n",
    "image_2 = cv2.imread(\"D:/picture/a54.jpg\", 0)\n",
    "image_3 = cv2.imread(\"D:/picture/a55.jpg\", 0)\n",
    "\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "image_2 = cv2.resize(image_2, (800, 500))\n",
    "image_3 = cv2.resize(image_3, (800, 500))\n",
    "\n",
    "photos.append(image_1)\n",
    "lables.append(0)\n",
    "photos.append(image_2)\n",
    "lables.append(0)\n",
    "photos.append(image_3)\n",
    "lables.append(0)\n",
    "\n",
    "image_4 = cv2.imread(\"D:/picture/a23.jpg\", 0)\n",
    "image_5 = cv2.imread(\"D:/picture/a24.jpg\", 0)\n",
    "image_6 = cv2.imread(\"D:/picture/a25.jpg\", 0)\n",
    "\n",
    "image_4 = cv2.resize(image_4, (800, 500))\n",
    "image_5 = cv2.resize(image_5, (800, 500))\n",
    "image_6 = cv2.resize(image_6, (800, 500))\n",
    "\n",
    "photos.append(image_4)\n",
    "lables.append(1)\n",
    "photos.append(image_5)\n",
    "lables.append(1)\n",
    "photos.append(image_6)\n",
    "lables.append(1)\n",
    "\n",
    "names = {\"0\": \"a_2\", \"1\": \"a_3\"}\n",
    "recognizer = cv2.face.FisherFaceRecognizer_create()\n",
    "recognizer.train(photos, np.array(lables))\n",
    "\n",
    "image = cv2.imread(\"D:/picture/a45.jpg\", 0)\n",
    "image = cv2.resize(image, (800, 500))\n",
    "\n",
    "label, confidence = recognizer.predict(image)\n",
    "print(\"confidence =\" + str(confidence))\n",
    "print(names[str(label)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Local Binary Pattern Histogram人脸识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "confidence =103.69430638776062\n",
      "a_3\n"
     ]
    }
   ],
   "source": [
    "photos = list()\n",
    "lables = list()\n",
    "\n",
    "image_1 = cv2.imread(\"D:/picture/a23.jpg\", 0)\n",
    "image_2 = cv2.imread(\"D:/picture/a24.jpg\", 0)\n",
    "image_3 = cv2.imread(\"D:/picture/a25.jpg\", 0)\n",
    "\n",
    "image_1 = cv2.resize(image_1, (800, 500))\n",
    "image_2 = cv2.resize(image_2, (800, 500))\n",
    "image_3 = cv2.resize(image_3, (800, 500))\n",
    "\n",
    "photos.append(image_1)\n",
    "lables.append(0)\n",
    "photos.append(image_2)\n",
    "lables.append(0)\n",
    "photos.append(image_3)\n",
    "lables.append(0)\n",
    "\n",
    "image_4 = cv2.imread(\"D:/picture/a33.jpg\", 0)\n",
    "image_5 = cv2.imread(\"D:/picture/a34.jpg\", 0)\n",
    "image_6 = cv2.imread(\"D:/picture/a35.jpg\", 0)\n",
    "\n",
    "image_4 = cv2.resize(image_4, (800, 500))\n",
    "image_5 = cv2.resize(image_5, (800, 500))\n",
    "image_6 = cv2.resize(image_6, (800, 500))\n",
    "\n",
    "photos.append(image_4)\n",
    "lables.append(1)\n",
    "photos.append(image_5)\n",
    "lables.append(1)\n",
    "photos.append(image_6)\n",
    "lables.append(1)\n",
    "\n",
    "names = {\"0\": \"a_2\", \"1\": \"a_3\"}\n",
    "recognizer = cv2.face.LBPHFaceRecognizer_create()\n",
    "recognizer.train(photos, np.array(lables))\n",
    "\n",
    "image = cv2.imread(\"D:/picture/a45.jpg\", 0)\n",
    "image = cv2.resize(image, (800, 500))\n",
    "\n",
    "label, confidence = recognizer.predict(image)\n",
    "print(\"confidence =\" + str(confidence))\n",
    "print(names[str(label)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
